﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using XbdSoft.Contract;
using XbdSoft.Domain;
using System.Net;
using System.Configuration;

namespace XbdSoft.Services
{
    public class DownloadService:IDownloadService
    {
        private const string DownloadInfoUrlKey = "infoUrl";
        private const string UsePassKey = "usepass";
        private const int DefaultClassParentID = 151;

        #region IDownloadService Members

        public string GetDownloadUrl(long resourceID)
        {
            var siteUrl = string.Format("http://www.xbd61.com/show_mp3.asp?S=9&ArticleID={0}", resourceID); 
            return siteUrl; 
        }

        public string GetDownloadInfoUrl()
        {
            return ConfigurationManager.AppSettings[DownloadInfoUrlKey] ?? "http://www.xbd61.com/";
        }

        public List<AudioCategory> GetRecommendDownloadCategories()
        {
            var recommendAudioCategories = new List<AudioCategory>();
            try
            {
                using (var context = new XbdDbContext(Constants.DownloadConnectionString))
                {
                    recommendAudioCategories = context.AudioCategories.Include("AudioResources").Where(c=>c.TjFlag==1).ToList();
                }
            }
            catch(Exception ex) { }
            return recommendAudioCategories;
        }

        public List<AudioCategory> GetAllDownloadCategories()
        {
            var recommendAudioCategories = new List<AudioCategory>();
            using (var context = new XbdDbContext(Constants.DownloadConnectionString))
            {
                recommendAudioCategories = context.AudioCategories.Where(c => c.TjFlag == 1).ToList();
            }
            return recommendAudioCategories;
        }

        public AudioResource GetAudioResource(long resourceID)
        {
            var result = default(AudioResource);
            using (var context = new XbdDbContext(Constants.DownloadConnectionString))
            {
                result = context.AudioResources.SingleOrDefault(r => r.ID == resourceID);
            }
            return result;
        }

        public List<AudioResource> GetAudioResourcesOfCategory(int categoryId)
        {
            var allAudioResources = new List<AudioResource>();
            using (var context = new XbdDbContext(Constants.DownloadConnectionString))
            {
                allAudioResources = context.AudioResources.Where(r => r.AudioCategoryID == categoryId).OrderByDescending(r=>r.ID).ToList();
            }
            return allAudioResources;
        }

        public AudioResourceDTO GetAudioResources(string keyword, int pageIndex,int pageSize)
        {
            var dto = new AudioResourceDTO();
            using (var context = new XbdDbContext(Constants.DownloadConnectionString))
            {
                var resources = context.AudioResources.Where(r => (r.Title != null&&r.Passed && r.Title.Contains(keyword)));
                var totalCouont = resources.Count();
                dto.TotalCount = totalCouont;
                if (pageSize * pageIndex < totalCouont)
                {
                    dto.AudioResources = resources.OrderByDescending(r => r.ID)
                                                    .Skip(pageSize * (pageIndex))
                                                    .Take(pageSize)
                                                    .ToList();
                }
                else
                {
                    dto.AudioResources = new List<AudioResource>();
                }                                                    
            }
            return dto;
        }

        public int GetAudioResourcesCount(string keyword)
        {
            using (var context = new XbdDbContext(Constants.DownloadConnectionString))
            {
                return context.AudioResources.Where(r => (r.Title != null && r.Passed && r.Title.Contains(keyword))).Count();
            }
        }

        public List<AudioClass> GetToShowAudioClasses()
        {
            using (var context = new XbdDbContext(Constants.DownloadConnectionString))
            {
                return context.AudioClasses.Where(r =>r.IsElite && r.ShowOnTop && r.ParentID ==DefaultClassParentID ).ToList();
            }
        }

        public AudioResourceDTO GetToShowAudioResourcesByAge(int ageIndex, int pageIndex, int pageSize)
        {
            var dto = new AudioResourceDTO();
            using (var context = new XbdDbContext(Constants.DownloadConnectionString))
            {
                IEnumerable<AudioResource> resources = default(IEnumerable<AudioResource>);
                if (ageIndex > 0)
                {
                    //resources = context.AudioResources.Where(r => ageIndexs.Any(a => r.SuitableAges.Contains(a.ToString())));
                    var ageStr = ageIndex.ToString();
                    resources = context.AudioResources.Where(r => r.Passed && !r.Deleted && r.SuitableAges.Contains(ageStr));
                }
                else {
                    resources = context.AudioResources.Where(r=>r.Passed && !r.Deleted );
                }
                
                var totalCouont = resources.Count();
                dto.TotalCount = totalCouont;
                if (pageSize * pageIndex < totalCouont)
                {
                    dto.AudioResources = resources.OrderByDescending(r => r.ID)
                                                    .Skip(pageSize * (pageIndex))
                                                    .Take(pageSize)
                                                    .ToList();
                }
                else
                {
                    dto.AudioResources = new List<AudioResource>();
                }
            }
            return dto;
        }

        public AudioResourceDTO GetToShowAudioResources(string keyword, int classID, int age, int pageIndex, int pageSize)
        {
            var ageStr =age.ToString();
            var dto = new AudioResourceDTO();
            using (var context = new XbdDbContext(Constants.DownloadConnectionString))
            {
                IEnumerable<AudioResource> resources = default(IEnumerable<AudioResource>);
                if (classID == DefaultClassParentID)
                {
                    var allClasses = (from reClass in context.AudioClasses
                                      where reClass.IsElite && reClass.ShowOnTop && reClass.ParentID == classID 
                                      select reClass);
                    
                    resources =( from resource in context.AudioResources  
                                where !resource.Deleted && resource.Title != null && resource.Title.Contains(keyword) && resource.Passed
                                       && allClasses.Any(c=>c.ID == resource.ClassID)
                                select resource); 
                }
                else
                {
                    resources = context.AudioResources.Where(r => (r.ClassID==classID &&r.Passed && !r.Deleted && r.Title != null && r.Title.Contains(keyword)));
                }
                if (age > 0)
                {
                    resources = resources.Where(r => r.SuitableAges.Contains(ageStr));
                }

                var totalCouont = resources.Count();
                dto.TotalCount = totalCouont;
                if (pageSize * pageIndex < totalCouont)
                {
                    dto.AudioResources = resources.OrderByDescending(r => r.ID)
                                                    .Skip(pageSize * (pageIndex))
                                                    .Take(pageSize)
                                                    .ToList();
                }
                else
                {
                    dto.AudioResources = new List<AudioResource>();
                }
            }
            return dto;
        }

        public string GetUsePassword()
        {
            return ConfigurationManager.AppSettings[UsePassKey] ?? string.Empty;
        }
        #endregion

        #region Advertisement

        public List<AdvertisementMimi> GetAllAdvertisementMimis()
        {
            using (var context = new XbdDbContext(Constants.LoginConnectionString))
            {
                return context.AdvertisementMimis.Where(m => m.ChannelID == 1 && m.IsSelected).ToList();
            }
        }
        public AdvertisementMimi GetDefaultAdvertisementMimi()
        {
            using (var context = new XbdDbContext(Constants.LoginConnectionString))
            {
                return context.AdvertisementMimis.FirstOrDefault(m => m.ChannelID == 1 && m.IsSelected);
            }
        }
        #endregion
    }
}
